<route lang="json5">
{
  style: {
    navigationBarTitleText: 'WiFi配网',
  },
}
</route>

<template>
  <view class="wifi-config">
    <view class="guide">
      <view class="guide-title">连接设备</view>
      <view class="guide-desc">请选择设备的WiFi进行连接</view>
    </view>

    <!-- WiFi列表 -->
    <view class="wifi-list">
      <view
        v-for="item in wifiList"
        :key="item.SSID"
        class="wifi-item"
        @tap="showConnectDialog(item)"
      >
        <view class="wifi-info">
          <text class="wifi-name">{{ item.SSID }}</text>
          <text class="wifi-signal">信号强度: {{ item.signalStrength }}%</text>
        </view>
        <text class="wifi-secure" v-if="item.secure">已加密</text>
      </view>
    </view>

    <!-- 刷新按钮 -->
    <view class="refresh-btn" @tap="refreshWifiList">
      <text>刷新WiFi列表</text>
    </view>

    <!-- 连接弹窗 -->
    <view class="connect-dialog" v-if="showDialog">
      <view class="dialog-content">
        <view class="dialog-title">连接 {{ selectedWifi?.SSID }}</view>
        <input
          class="password-input"
          v-model="wifiPassword"
          type="text"
          password
          placeholder="请输入WiFi密码"
        />
        <view class="dialog-btns">
          <button class="cancel-btn" @tap="closeDialog">取消</button>
          <button
            class="confirm-btn"
            :disabled="!wifiPassword"
            :loading="isConnecting"
            @tap="connectWifi"
          >
            {{ isConnecting ? '连接中...' : '连接' }}
          </button>
        </view>
      </view>
    </view>

    <!-- 加载提示 -->
    <view class="loading" v-if="isLoading">
      <text>搜索WiFi中...</text>
    </view>

    <view class="retry-btn" v-if="initFailed" @tap="retryInit">
      <text>重新初始化</text>
    </view>
  </view>
</template>

<script lang="ts" setup>
const wifiList = ref<WechatMiniprogram.GetWifiListSuccessCallbackResult[]>([])
const selectedWifi = ref<WechatMiniprogram.WiFi>()
const wifiPassword = ref('')
const isLoading = ref(false)
const isConnecting = ref(false)
const initFailed = ref(false)
const showDialog = ref(false)

// 显示连接弹窗
const showConnectDialog = (wifi: WechatMiniprogram.WiFi) => {
  selectedWifi.value = wifi
  wifiPassword.value = ''
  showDialog.value = true
}

// 关闭弹窗
const closeDialog = () => {
  showDialog.value = false
  selectedWifi.value = undefined
  wifiPassword.value = ''
}

// 连接WiFi
const connectWifi = async () => {
  if (!selectedWifi.value || !wifiPassword.value) return

  isConnecting.value = true
  try {
    await wx.connectWifi({
      SSID: selectedWifi.value.SSID,
      password: wifiPassword.value,
    })

    uni.showToast({
      title: '连接成功',
      icon: 'success',
    })

    // 延迟跳转,等待连接完全建立
    setTimeout(() => {
      uni.navigateTo({
        url: '/pages/device-config/index',
      })
    }, 1000)
  } catch (err) {
    uni.showToast({
      title: '连接失败',
      icon: 'error',
    })
    console.error('WiFi连接失败:', err)
  } finally {
    isConnecting.value = false
    closeDialog()
  }
}

// 初始化WiFi
const initWifi = async () => {
  isLoading.value = true
  initFailed.value = false
  try {
    // 1. 检查位置权限
    const locationRes = await uni.authorize({
      scope: 'scope.userLocation',
    })

    // 2. 初始化 WiFi 模块
    const startWifiRes = await wx.startWifi()
    console.log('WiFi初始化结果:', startWifiRes)

    // 3. 获取 WiFi 列表
    const getWifiListRes = await wx.getWifiList()
    console.log('获取WiFi列表结果:', getWifiListRes)
  } catch (err) {
    console.error('WiFi初始化失败:', err)

    // 根据错误类型显示不同提示
    if (err.errCode === 12005) {
      uni.showModal({
        title: '提示',
        content: '请开启手机定位功能',
        showCancel: false,
      })
    } else if (err.errCode === 12006) {
      uni.showModal({
        title: '提示',
        content: '请授权位置权限',
        success: (res) => {
          if (res.confirm) {
            uni.openSetting()
          }
        },
      })
    } else {
      uni.showToast({
        title: `WiFi初始化失败: ${err.errMsg}`,
        icon: 'none',
      })
    }
    isLoading.value = false
    initFailed.value = true
  }
}

// 刷新WiFi列表
const refreshWifiList = () => {
  initWifi()
}

// 监听WiFi列表
wx.onGetWifiList((res) => {
  isLoading.value = false
  // 按信号强度排序
  wifiList.value = res.wifiList.sort((a, b) => b.signalStrength - a.signalStrength)
})

// 添加重试函数
const retryInit = () => {
  initWifi()
}

// 页面加载时初始化WiFi
onLoad(() => {
  initWifi()
})
</script>

<style lang="scss" scoped>
.wifi-config {
  min-height: 100vh;
  padding: 20px;
  background: #f5f5f5;
}

.guide {
  margin-bottom: 30px;
  text-align: center;

  &-title {
    margin-bottom: 10px;
    font-size: 24px;
    font-weight: bold;
    color: #333;
  }

  &-desc {
    font-size: 14px;
    color: #666;
  }
}

.wifi-list {
  padding: 10px;
  margin-bottom: 20px;
  background: #fff;
  border-radius: 12px;
}

.wifi-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 15px;
  border-bottom: 1px solid #eee;

  &:last-child {
    border-bottom: none;
  }

  &-selected {
    background: #e6f7ff;
  }
}

.wifi-info {
  flex: 1;
}

.wifi-name {
  margin-bottom: 4px;
  font-size: 16px;
  color: #333;
}

.wifi-signal {
  font-size: 12px;
  color: #999;
}

.wifi-secure {
  font-size: 12px;
  color: #52c41a;
}

.refresh-btn {
  padding: 10px;
  font-size: 14px;
  color: #1890ff;
  text-align: center;
}

.wifi-form {
  padding: 20px;
  background: #fff;
  border-radius: 12px;

  .form-title {
    margin-bottom: 15px;
    font-size: 16px;
    color: #333;
  }
}

.password-input {
  width: 100%;
  height: 44px;
  padding: 0 15px;
  margin-bottom: 20px;
  font-size: 14px;
  border: 1px solid #ddd;
  border-radius: 6px;
}

.config-btn {
  width: 100%;
  height: 44px;
  font-size: 16px;
  color: #fff;
  background: #1890ff;
  border-radius: 6px;

  &[disabled] {
    background: #ccc;
  }
}

.loading {
  position: fixed;
  top: 50%;
  left: 50%;
  padding: 10px 20px;
  font-size: 14px;
  color: #fff;
  background: rgba(0, 0, 0, 0.7);
  border-radius: 4px;
  transform: translate(-50%, -50%);
}

.retry-btn {
  padding: 10px;
  margin-top: 20px;
  font-size: 14px;
  color: #1890ff;
  text-align: center;
}

.connect-dialog {
  position: fixed;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  background: rgba(0, 0, 0, 0.6);

  .dialog-content {
    width: 80%;
    padding: 20px;
    background: #fff;
    border-radius: 12px;
  }

  .dialog-title {
    margin-bottom: 20px;
    font-size: 18px;
    color: #333;
    text-align: center;
  }

  .dialog-btns {
    display: flex;
    margin-top: 20px;

    button {
      flex: 1;
      height: 40px;
      margin: 0 10px;
      font-size: 16px;
      border-radius: 6px;
    }

    .cancel-btn {
      color: #666;
      background: #f5f5f5;
    }

    .confirm-btn {
      color: #fff;
      background: #1890ff;

      &[disabled] {
        background: #ccc;
      }
    }
  }
}
</style>
